#!/bin/bash

# Set Variables
COLXML='/etc/columnstore/Columnstore.xml'
IFLAG='/etc/columnstore/container-initialized'
LOG_PREFIX='/var/log/mariadb/columnstore'
MCS_INSTALL_BIN='/usr/bin'
TOTALUMMEMORY="${TOTALUMMEMORY:-25%}"
NUMBLOCKSPCT="${NUMBLOCKPCT:-50}"


echo "[Starting MariaDB Columnstore]"

# Intialize Container If Necessary
if [ ! -e $IFLAG ]; then
    $MCS_INSTALL_BIN/columnstore-init &> /var/log/mariadb/columnstore/columnstore-init.log
    if [ $? -ne 0 ]; then
        echo "ERROR: During Initialization."
        exit 1
    fi
fi

# Dynamic Memory Allocation
if [ -f /sys/fs/cgroup/memory/memory.limit_in_bytes ] && [ "$(cat /sys/fs/cgroup/memory/memory.limit_in_bytes)" -le "$(free -b | awk 'NR==2{printf "%d", $2 }')" ]; then
    MAX_RAM_BYTES=$(cat /sys/fs/cgroup/memory/memory.limit_in_bytes)
    MAX_RAM=$((MAX_RAM_BYTES/1024/1024))
    TOTALUMMEMORY=$( echo $MAX_RAM / 4  | bc )M
    NUMBLOCKSPCT=$( echo $MAX_RAM / 2  | bc )M
fi

# Performance Tuning
xmlstarlet ed -L -u '/Columnstore/HashJoin/TotalUmMemory' -v "$TOTALUMMEMORY" $COLXML
xmlstarlet ed -L -u '/Columnstore/DBBC/NumBlocksPct' -v "$NUMBLOCKSPCT" $COLXML

# Start cmapi
echo 'Starting CMAPI...'

touch $LOG_PREFIX/cmapi_server.log && chmod 666 $LOG_PREFIX/cmapi_server.log
cd /usr/share/columnstore/cmapi || exit
PYTHONPATH=/usr/share/columnstore/cmapi/deps /usr/share/columnstore/cmapi/python/bin/python3 -m cmapi_server &> $LOG_PREFIX/cmapi_server.log &
echo "CMAPI PID = $!"

# Start MariaDB
if [ ! -z "$(pidof mariadbd)" ]; then
    /etc/init.d/mariadb restart
else
    /etc/init.d/mariadb start
fi

exit 0
